import Vue from 'vue'
import Vuex from 'vuex'
import { fetchConfig } from '@/api/system'
Vue.use(Vuex)

const state = {
  // 登录用户信息
  userInfo: null,
  // 首页
  homePage: null,
  // 客户端配置
  clientConfig: null,
  // 菜单
  menuData: {
    // 菜单列表
    list: [],
    // 是否收起
    collapse: false
  },
  // 缓存内容
  cache: {}
}

const mutations = {
  // 切换菜单状态
  switchCollapseMenu (state, value) {
    if (value != null) {
      state.menuData.collapse = value
    } else {
      state.menuData.collapse = !state.menuData.collapse
    }
    window.localStorage.setItem('MENU_STATUS', state.menuData.collapse)
  },
  // 设置已登录的用户信息
  setUserInfo: (state, data) => {
    state.userInfo = data
  },
  // 设置首页路由信息
  setHomePage (state, homePage) {
    state.homePage = homePage
  },
  // 设置客户端配置
  setClientConfig (state, clientConfig) {
    state.clientConfig = clientConfig
  },
  // 重置菜单
  resetMenus: (state) => {
    state.menuData.list = []
  },
  // 合并缓存
  mergeCache (state, data) {
    for (const key in data) {
      // 删除data中为null的字段
      if (data[key] == null) {
        delete state.cache[key]
      }
      // 覆盖缓存值
      state.cache[key] = data[key]
    }
  }
}
const actions = {
  /**
   * 初始化客户端配置
   */
  initClientConfig ({ commit }) {
    return fetchConfig()
  }
}
const getters = {}
export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
})
